package com.jdy.haoduoai.activity;

import android.Manifest.permission;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.AssetFileDescriptor;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PreviewCallback;
import android.hardware.Camera.Size;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.Result;
import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.intface.IAsyncTask;
import com.jdy.haoduoai.model.LeMachine;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.parse.JsonSerializer;
import com.jdy.haoduoai.scan.camera.CameraManager;
import com.jdy.haoduoai.scan.decode.Bitmap2QR;
import com.jdy.haoduoai.scan.decode.CaptureActivityHandler;
import com.jdy.haoduoai.socket.SocketThreadManager;
import com.jdy.haoduoai.util.CustomAsyncTask;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.LeConfig;
import com.jdy.haoduoai.util.OnDataReceivedListener;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.jdy.haoduoai.view.CameraPreview;
import com.jdy.haoduoai.widget.BindSuccessOneBtnDialog;
import com.jdy.haoduoai.widget.CustomEditDialog;
import com.jdy.haoduoai.widget.CustomOneBtnDialog;
import com.jdy.haoduoai.widget.CustomTipDialog;
import com.umeng.analytics.MobclickAgent;
import com.ycsj.goldmedalnewconcept.R;

import net.sourceforge.zbar.Config;
import net.sourceforge.zbar.Image;
import net.sourceforge.zbar.ImageScanner;
import net.sourceforge.zbar.Symbol;
import net.sourceforge.zbar.SymbolSet;

import org.droidparts.annotation.inject.InjectView;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.StringTokenizer;

//import com.jdy.haoduoai.R;

/**
 * 绑定设备
 *
 * @author Administrator
 *
 */
@SuppressWarnings("deprecation")
public class BindDeviceActivity extends BaseActivity implements
        OnDataReceivedListener {

  @InjectView(id = R.id.tv_title)
  private TextView mScanTextTextView;
  @InjectView(id = R.id.cameraPreview)
  private FrameLayout preview;
  @InjectView(id = R.id.cameraScanBackImageView)
  private ImageView mBackImageView;
  @InjectView(id = R.id.selecteImageFromGalleryImageView, click = true)
  private ImageView mPickImageView;
  @InjectView(id = R.id.img_selectlight, click = true)
  private ImageView img_selectlight;
  @InjectView(id = R.id.input_deviceid, click = true)
  private Button input_deviceid;
  @InjectView(id = R.id.operation_specification_tv, click = true)
  private TextView mOperationSpecificationTv;

  private CaptureActivityHandler handler;
  private LeUser mLeUser;
  private Camera mCamera;
  private Parameters mParameters;
  private CameraPreview mPreview;
  private Handler autoFocusHandler;

  private Handler mHandler = new Handler();
  private ImageScanner scanner;
  private boolean barcodeScanned = false;
  private boolean previewing = true;
  private boolean hasSurface;
  private static final long VIBRATE_DURATION = 200L;
  private static final int SELECT_PHOTO = 100;
  private MediaPlayer mediaPlayer;
  private boolean playBeep;
  private static final float BEEP_VOLUME = 0.10f;
  private boolean vibrate;
  private boolean isLightOn = false;
  private String mDeviceID;
  private String fromPage;

  static {
    System.loadLibrary("iconv");
  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.zbar_scan_layout);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    hideTitleView();

    bindService();

    CameraManager.init(getApplication());

    Intent intentData = getIntent();
    if (intentData != null) {
      fromPage = intentData.getStringExtra("fromPage");
    }

    hasSurface = false;
    mLeUser = LeXiaoXiaoBanApp.getInstance().getUser();
    autoFocusHandler = new Handler();
    mCamera = getCameraInstance(this);

    scanner = new ImageScanner();
    scanner.setConfig(0, Config.X_DENSITY, 3);
    scanner.setConfig(0, Config.Y_DENSITY, 3);

    mPreview = new CameraPreview(this, mCamera, previewCb, autoFocusCB);
    preview.addView(mPreview);

    mBackImageButton.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        if (Tools.isNotEmpty(fromPage)) {
          if (fromPage.contains("DevicePropertyActivity")) {
            // TODO
          } else {
            Intent intent0 = new Intent(BindDeviceActivity.this,
                LoginActivity.class);
            intent0.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            startActivity(intent0);
          }
        }

        finish();
      }
    });

    setListener();

  }

  private void checkUserImSig() {
    SocketThreadManager.getInstance().requestDeviceDetails();
  }

  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
      if (Tools.isNotEmpty(fromPage)) {
        if (fromPage.contains("DevicePropertyActivity")) {
          // TODO
        } else {
          Intent intent0 = new Intent(this, LoginActivity.class);
          intent0.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
          startActivity(intent0);
        }

        finish();
        return true;
      } else {
        return super.onKeyDown(keyCode, event);
      }

    }
    return super.onKeyDown(keyCode, event);
  }

  private void setListener() {
    mPreview.setSurfaceHolderCallback(new SurfaceHolder.Callback() {
      @Override
      public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;
      }

      @Override
      public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
          hasSurface = true;
          try {
            CameraManager.get().openDriver(holder, mCamera);
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
        if (handler == null) {
        }
      }

      @Override
      public void surfaceChanged(SurfaceHolder holder, int format, int width,
          int height) {
      }
    });

    mScanTextTextView.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        if (barcodeScanned) {
          barcodeScanned = false;
          mCamera.setPreviewCallback(previewCb);
          mCamera.startPreview();
          previewing = true;
          mCamera.autoFocus(autoFocusCB);
        }
      }
    });

    mBackImageView.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View v) {

        finish();
        overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
      }
    });

    mPickImageView.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        pickFromGallery();
      }
    });

    img_selectlight.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        isLightOn = !isLightOn;

        if (isLightOn) {
          img_selectlight.setImageResource(R.drawable.light_on);
          new Thread(new TurnOnLight()).start();
        } else {
          img_selectlight.setImageResource(R.drawable.light_off);

          if (Tools.isNotEmpty(mParameters.getFlashMode())
                  && !mParameters.getFlashMode().equalsIgnoreCase(Parameters.FLASH_MODE_OFF)) {
            mParameters.setFlashMode(Parameters.FLASH_MODE_OFF);
          }
          if (mCamera != null) {
            mCamera.setParameters(mParameters);
          }
        }
      }
    });

    input_deviceid.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        final CustomEditDialog.Builder customBuilder = new CustomEditDialog.Builder(
            BindDeviceActivity.this);
        customBuilder.setTitle("请输入绑定编号")
            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
              }
            }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int which) {
                mDeviceID = customBuilder.getEditText();
                if (Tools.isNotEmpty(mDeviceID)) {
                  bindDevice(dialog, false, mDeviceID.toLowerCase());
                } else {
                  toastShow("绑定编号不能为空!");
                }
              }
            });

        if (!isFinishing()) {
          customBuilder.create().show();
        }
      }
    });

    mOperationSpecificationTv.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View v) {
        showBindHelpDiglog();
      }
    });
  }

  private void showBindHelpDiglog() {
    CustomTipDialog.Builder cdb = new CustomTipDialog.Builder(this)
        .setPositiveButton(new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
          }
        });
    CustomTipDialog cd = cdb.create();
    cd.setCancelable(true);
    cd.setCanceledOnTouchOutside(true);
    cd.show();
  }

  private void bindSuccessTip(final boolean bIsTest) {
    BindSuccessOneBtnDialog.Builder cdb = new BindSuccessOneBtnDialog.Builder(
        BindDeviceActivity.this).setTitle("设备绑定成功")
        .setMessage("设备序列号：" + mDeviceID.toLowerCase())
        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
            checkMacActivation(mDeviceID);
          }
        });
    BindSuccessOneBtnDialog cd = cdb.create();
    cd.setCancelable(false);
    cd.setCanceledOnTouchOutside(false);

    if (!isFinishing()) {
      cd.show();
    }
  }

  private int totalMonth;

  /**
   * 判断宝宝年龄
   */
  private void checkBabyAge() {
    LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
    if (lu != null && Tools.isNotEmpty(lu.machine)) {
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

      try {
        Calendar bef = Calendar.getInstance();
        bef.setTime(sdf.parse(lu.machine.dob));

        int month = Calendar.getInstance().get(Calendar.MONTH)
            - bef.get(Calendar.MONTH);

        int year = Calendar.getInstance().get(Calendar.YEAR)
            - bef.get(Calendar.YEAR);

        totalMonth = year * 12 + month;
        if (totalMonth == 0) {
          totalMonth = 1;
        }

      } catch (Exception e) {
        // TODO: handle exception
      }
    }
  }

  private void doPageRoute() {
    checkBabyAge();

    if (LeConfig.isLogin) {
      if (LeConfig.isDeviceBinded) {
        if (LeConfig.isInfoFilled) {
          Intent intent = new Intent(BindDeviceActivity.this,
              MainActivity.class);
          intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
          startActivity(intent);
          overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);

          finish();

          if (LeConfig.isDeviceActivated) {

          } else {
          }
        } else {
          Intent t = new Intent(BindDeviceActivity.this,
              FillInfoPopupActivity.class);
          t.putExtra("fromPage", "BindDeviceActivity");
          startActivity(t);
          finish();
        }
      } else {
      }
    } else {
    }
  }

  private void checkMacActivation(final String macId) {
    LeMachine macInfo = LeXiaoXiaoBanApp.getInstance().getBaby();
    LeConfig.isInfoFilled = false;

    if (macInfo != null) {
      if (Tools.isNotEmpty(macInfo.name)) {
        if (mLeUser != null && Tools.isNotEmpty(mLeUser.nickname)
            && Tools.isNotEmpty(mLeUser.callname)) {
          LeConfig.isInfoFilled = true;
        }

        if (Tools.isNotEmpty(macInfo.activate)
            && !macInfo.activate.toString().equals("null")) {
          LeConfig.isDeviceActivated = !macInfo.activate.is_expired;
          LeConfig.expiredAt = macInfo.activate.expired_at;
        }
      }
    }

    doPageRoute();

    overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);

  }

  private void bindService() {
//    SocketThreadManager.getInstance().setDataReceivedListener(this);
//      try {
//        JSONObject dataJson = new JSONObject();
//        dataJson.put("code", 202);
//        dataJson.put("act", "machineinfo");
//        SocketThreadManager.getInstance().send(dataJson.toString());
//      } catch (JSONException e) {
//        e.printStackTrace();
//      } catch (Exception e) {
//        e.printStackTrace();
//      }
  }

  private void unBind() {

  }

  /**
   * 绑定设备
   *
   * @param dialog
   * @param bIsTest
   *          测试设备id
   * @param macId
   */
  private void bindDevice(final DialogInterface dialog, final boolean bIsTest,
      final String macId) {

    LeXiaoXiaoBanApp.getInstance().setUser(mLeUser);

    Tools.saveLeUser(mLeUser);

   final  String macidParam;
    if (bIsTest) {
      macidParam = "08d8334ebc24";
    } else {
      macidParam = macId;
    }

   // macidParam = "111111111111";

    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {

        if (result.isSuccess() && Tools.isNotNullStr(result.data)) { // 设备绑定成功
          if (dialog != null) {
            dialog.dismiss();
          }
          LeConfig.isDeviceBinded = true;
          LeMachine macInfo = JsonSerializer.getInstance().deserialize(
              result.data, LeMachine.class);

          LeConfig.MAC_ID = macInfo.id;

          String url = macInfo.ip;
          if (Tools.isNotNullStr(url)) {
            StringTokenizer tokens = new StringTokenizer(url, ":");
            LeConfig.g_ServerIP = tokens.nextToken();
            LeConfig.FILE_PORT = Integer.parseInt(tokens.nextToken());

             if (SocketThreadManager.getInstance() != null) {
             // SocketThreadManager.getInstance().stopThreads();
             SocketThreadManager.getInstance().releaseInstance();
             SocketThreadManager.getInstance();
             SocketThreadManager.getInstance().disconnectOldConnectNew();
             }
          }

          // 更新用户、设备信息
          LeXiaoXiaoBanApp.getInstance().setBaby(macInfo);
          Tools.saveLeBaby(macInfo);

          checkUserImSig();

          LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
          if (lu != null) {
            lu.machine = macInfo; // );
          }

          bindSuccessTip(bIsTest);
        } else {
          LeConfig.isDeviceBinded = false;
          if (Tools.isNotNullStr(result.data)) {
            toastShow(result.data);

            if (result.status == -5 || result.data.contains("设备未注册")
                || result.data.contains("设备不存在")) {
              CustomOneBtnDialog.Builder cdb = new CustomOneBtnDialog.Builder(
                  BindDeviceActivity.this)
                  .setTitle("温馨提示")
                  .setMessage("绑定设备之前，请先确保您的小小班设备已经连上网络。")
                  .setPositiveButton("确定",
                      new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                          dialog.dismiss();

                          Intent intent2 = new Intent(BindDeviceActivity.this,
                              ConnectWifiActivity.class);
                          intent2.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
                              | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                          startActivity(intent2);
                          overridePendingTransition(R.anim.push_left_in,
                              R.anim.push_left_out);
                        }
                      });
              CustomOneBtnDialog cd = cdb.create();
              cd.setCancelable(false);
              cd.setCanceledOnTouchOutside(false);
              cd.show();
            } else {

              mHandler.postDelayed(new Runnable() {

                @Override
                public void run() {
                  previewing = true;
                  if (mCamera != null) {
                    mCamera.setPreviewCallback(previewCb);
                    mCamera.startPreview();
                    mCamera.autoFocus(autoFocusCB);
                  }
                }
              }, 2000);
            }

          }
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        if (mLeUser == null) {
          mLeUser = Tools.restoreLeUser();
        }

        HashMap<String, Object> param_ = new HashMap<String, Object>();

        param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
        param_.put("machine_id", macidParam);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

        return HttpUtils.startRequest(HttpUtils.HOST_API
            + HttpUtils.BIND_DEVICE_METHOD_POST, param_,
            HttpUtils.TAG_POST_REQUEST);
      }
    }).execute();
  }

  private class TurnOnLight implements Runnable {
    @Override
    public void run() {

      if (mCamera != null) {

        mParameters = mCamera.getParameters();


        if (Tools.isNotEmpty(mParameters.getFlashMode())) {
          if (!mParameters.getFlashMode().equalsIgnoreCase(Parameters.FLASH_MODE_TORCH)) {
            mParameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
          }
        } else {
// // TODO: 2017/8/29
        }

        if (mCamera != null) {
          mCamera.setParameters(mParameters);
        }
      }
    }
  }

  private void pickFromGallery() {
    try {
      Intent intent = new Intent(Intent.ACTION_PICK, null);
      intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
          "image/*");
      startActivityForResult(intent, SELECT_PHOTO);
      overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    } catch (ActivityNotFoundException e) {
      toastShow("找不到系统相册！");
    }
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode,
      Intent imageReturnedIntent) {
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
    switch (requestCode) {
    case SELECT_PHOTO:
      if (resultCode == RESULT_OK) {
        Result result = null;
        try {
          InputStream is = getContentResolver().openInputStream(
              imageReturnedIntent.getData());
          result = Bitmap2QR.scanningImage(is);
        } catch (FileNotFoundException e) {
          e.printStackTrace();
        }

        if (result != null) {
          handleDecode(result);
        } else {
          Toast.makeText(this, "识别失败", Toast.LENGTH_LONG).show();
        }
      }
    }
  }

  @Override
  protected void onResume() {
    super.onResume();

    MobclickAgent.onResume(this);

    playBeep = true;
    AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
    if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
      playBeep = false;
    }
    initBeepSound();
    vibrate = true;
  }

  @Override
  public void onPause() {
    super.onPause();
    MobclickAgent.onPause(this);
    // releaseCamera();
    if (handler != null) {
      handler.quitSynchronously();
      handler = null;
    }
  }

  @Override
  public void onDestroy() {
    super.onDestroy();

    unBind();

    SocketThreadManager.getInstance().removeDataReceivedListener(this);

    img_selectlight.setImageResource(R.drawable.light_off);

    if (mParameters == null) {
      try {
        mParameters = mCamera.getParameters();
      } catch (RuntimeException e) {
        // TODO: handle exception
      }
    }

    if (mHandler != null) {
      mHandler.removeCallbacksAndMessages(null);
      mHandler = null;
    }

    if (mParameters != null) {
      if (Tools.isNotEmpty(mParameters.getFlashMode())
              && !mParameters.getFlashMode().equalsIgnoreCase(Parameters.FLASH_MODE_OFF)) {
        mParameters.setFlashMode(Parameters.FLASH_MODE_OFF);
      }

      if (mCamera != null) {
        mCamera.setParameters(mParameters);
      }
    }

    releaseCamera();
  }

  /** A safe way to get an instance of the Camera object. */
  public Camera getCameraInstance(Context context) {
    Camera c = null;
    if (Tools.checkCameraHardware(context)) {
      if (Tools.checkPermission(context, permission.CAMERA)) {
        try {
          c = Camera.open();
        } catch (Exception e) {
        }
      } else {
        toastShow("请允许好多爱家长版使用相机权限以使用此功能.");
      }
    } else {
      toastShow("抱歉，您的设备没有相机.");
    }
    return c;
  }

  private void releaseCamera() {
    if (mCamera != null) {
      previewing = false;
      mCamera.setPreviewCallback(null);
      mCamera.stopPreview();
      mCamera.release();
      mCamera = null;
    }
  }

  private final Runnable doAutoFocus = new Runnable() {
    @Override
    public void run() {
      if (previewing) {
        mCamera.autoFocus(autoFocusCB);
      }
      // viewfinderView.drawViewfinder();
    }
  };

  private final PreviewCallback previewCb = new PreviewCallback() {
    @Override
    public void onPreviewFrame(byte[] data, Camera camera) {
      Parameters parameters = camera.getParameters();
      Size size = parameters.getPreviewSize();
      Image barcode = new Image(size.width, size.height, "Y800");
      barcode.setData(data);
      handleDecode(barcode);
    }
  };

  private void initBeepSound() {
    if (playBeep && mediaPlayer == null) {
      // The volume on STREAM_SYSTEM is not adjustable, and users found it
      // too loud,
      // so we now play on the music stream.
      setVolumeControlStream(AudioManager.STREAM_MUSIC);
      mediaPlayer = new MediaPlayer();
      mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
      mediaPlayer.setOnCompletionListener(beepListener);

      AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
      try {
        mediaPlayer.setDataSource(file.getFileDescriptor(),
            file.getStartOffset(), file.getLength());
        file.close();
        mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
        mediaPlayer.prepare();
      } catch (IOException e) {
        mediaPlayer = null;
      }
    }
  }

  private void playBeepSoundAndVibrate() {
    if (playBeep && mediaPlayer != null) {
      mediaPlayer.start();
    }
    if (vibrate) {
      Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
      vibrator.vibrate(VIBRATE_DURATION);
    }
  }

  /**
   * When the beep has finished playing, rewind to queue up another one.
   */
  private final OnCompletionListener beepListener = new OnCompletionListener() {
    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
      mediaPlayer.seekTo(0);
    }
  };

  private void handleDecode(Image barcode) {
    int result = scanner.scanImage(barcode);
    if (result != 0) {
      previewing = false;
      mCamera.setPreviewCallback(null);
      mCamera.stopPreview();

      SymbolSet syms = scanner.getResults();

      if (Tools.isNotEmpty(syms)) {
        for (Symbol sym : syms) {
          Intent resultIntent = new Intent();
          Bundle bundle = new Bundle();
          bundle.putString("result", sym.getData());
          resultIntent.putExtras(bundle);
          setResult(RESULT_OK, resultIntent);
          mDeviceID = sym.getData().toString().trim();
          bindDevice(null, false, mDeviceID.toLowerCase());
          barcodeScanned = true;
          playBeepSoundAndVibrate();
          break;
        }
      }

    }
  }

  public void handleDecode(final Result obj) {
    if (Tools.isNotEmpty(obj)) {
      if (Tools.isNotEmpty(obj.getText())) {
        previewing = false;
        mCamera.setPreviewCallback(null);
        mCamera.stopPreview();

        Intent resultIntent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putString("result", obj.getText());
        resultIntent.putExtras(bundle);
        setResult(RESULT_OK, resultIntent);
        mDeviceID = obj.getText().toString().trim();
        bindDevice(null, false, mDeviceID.toLowerCase());
        barcodeScanned = true;
        playBeepSoundAndVibrate();
      }
    } else {
      Toast.makeText(this, "识别二维码失败,请重新尝试", Toast.LENGTH_LONG).show();
      finish();
    }
  }

  private final AutoFocusCallback autoFocusCB = new AutoFocusCallback() {
    @Override
    public void onAutoFocus(boolean success, Camera camera) {
      autoFocusHandler.postDelayed(doAutoFocus, 1000);
    }
  };

  private boolean isImLogin;
  private String lastIMContent;

  @Override
  public void onDataReceived(final String data) {

    runOnUiThread(new Runnable() {
      @Override
      public void run() {
        if (Tools.isNotEmpty(data)) {
          try {
            JSONObject jsonData = new JSONObject(data.toString());
            if (Tools.isNotEmpty(jsonData) && !jsonData.isNull("code")
                    && jsonData.getString("code").contains("server")) {
              String loginStr = jsonData.getString("act");
              if (Tools.isNotEmpty(loginStr)) {
                if (loginStr.contains("Device_Login")) {
                  LeConfig.isDeviceConnect = true;
                } else if (loginStr.contains("Device_Logout")) {
                  LeConfig.isDeviceConnect = false;
                } else if (loginStr.contains("Device_APP_Connection_Switched")) {
                  // Jump to Login page

                  // Intent logoutIntent = new Intent(
                  // "com.jdy.haoduoai.activity.logout");
                  // sendBroadcast(logoutIntent);
                  //
                  // LeConfig.isLogin = false;
                  // LeConfig.isDeviceActivated = false;
                  // LeConfig.isDeviceBinded = false;
                  // LeConfig.isInfoFilled = false;
                  // LeConfig.isDeviceConnect = false;
                  //
                  // CustomOneBtnDialog.Builder cdb = new
                  // CustomOneBtnDialog.Builder(
                  // getApplicationContext())
                  // .setTitle("下线通知")
                  // .setMessage("您有其他亲友正在连接控制小小班设备，请休息片刻。")
                  // .setPositiveButton("确定",
                  // new DialogInterface.OnClickListener() {
                  //
                  // @Override
                  // public void onClick(DialogInterface dialog, int which) {
                  // dialog.dismiss();
                  // }
                  // });
                  // final CustomOneBtnDialog cd = cdb.create();
                  // cd.getWindow().setType(
                  // WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                  // cd.setOnDismissListener(new OnDismissListener() {
                  //
                  // @Override
                  // public void onDismiss(DialogInterface dialog) {
                  // Intent toActivityIntent = new Intent(BindDeviceActivity.this,
                  // LoginActivity.class);
                  // toActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
                  // | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                  // startActivity(toActivityIntent);
                  // finish();
                  // // dialog.dismiss();
                  // }
                  // });
                  // // cd.setCancelable(false);
                  // // cd.setCanceledOnTouchOutside(false);
                  // cd.show();
                }
              }
            } else if (Tools.isNotEmpty(jsonData) && !jsonData.isNull("code")
                    && jsonData.getString("code").contains("device")) {
              String loginStr = jsonData.getString("act");
              if (Tools.isNotEmpty(loginStr)) {
                if (loginStr.contains("Device_Login")) {
                  LeConfig.isDeviceConnect = true;
                } else if (loginStr.contains("Device_Logout")) {
                  LeConfig.isDeviceConnect = false;
                } else if (loginStr.contains("Device_APP_Connection_Switched")) {
                  // Jump to Login page

                  // Intent logoutIntent = new Intent(
                  // "com.jdy.haoduoai.activity.logout");
                  // sendBroadcast(logoutIntent);
                  //
                  // LeConfig.isLogin = false;
                  // LeConfig.isDeviceActivated = false;
                  // LeConfig.isDeviceBinded = false;
                  // LeConfig.isInfoFilled = false;
                  // LeConfig.isDeviceConnect = false;
                  //
                  // CustomOneBtnDialog.Builder cdb = new
                  // CustomOneBtnDialog.Builder(
                  // getApplicationContext())
                  // .setTitle("下线通知")
                  // .setMessage("您有其他亲友正在连接控制小小班设备，请休息片刻。")
                  // .setPositiveButton("确定",
                  // new DialogInterface.OnClickListener() {
                  //
                  // @Override
                  // public void onClick(DialogInterface dialog, int which) {
                  // dialog.dismiss();
                  // }
                  // });
                  // final CustomOneBtnDialog cd = cdb.create();
                  // cd.getWindow().setType(
                  // WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                  // cd.setOnDismissListener(new OnDismissListener() {
                  //
                  // @Override
                  // public void onDismiss(DialogInterface dialog) {
                  // Intent toActivityIntent = new Intent(BindDeviceActivity.this,
                  // LoginActivity.class);
                  // toActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
                  // | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                  // startActivity(toActivityIntent);
                  // finish();
                  // // dialog.dismiss();
                  // }
                  // });
                  // // cd.setCancelable(false);
                  // // cd.setCanceledOnTouchOutside(false);
                  // cd.show();
                }
              }
            }
          } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }
      }
    });




  }
}